import React, { PureComponent } from 'react'
import { Card, Divider, message, Button,PageHeader } from 'antd'
import { connect } from 'dva'
import PropTypes from 'prop-types'
import { routerRedux } from 'dva/router'
import * as R from 'ramda'
import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import FooterToolbar from '@/components/FooterToolbar'
import { PrimaryButton } from '@/support/components/Buttons'
import VehicleInfo from './components/VehicleInfo'
import VehicleStatus from './components/VehicleStatus'
import VehicleFlow from './components/VehicleFlow'
import OwerProfile from './components/OwerProfile'
import SIMDetailModal from '@/components/simCard/simCardDetailModal'
import { DFPVCanLogTab, DFPVHistoryTab, DFPVRcUerInfoTab, DFPVTboxBusinessLogTab, DFPVTboxLogTab, DFPVWheelPathTab, TboxTimeScaledTab } from './tabs/DFPVTabs'
import { HMTboxLogTable, HMWheelPathTable } from './tabs/HAIMATabs'
import { VehicleStatusListTable,SGMWWheelPathTab } from './tabs/SGMWTabs'
import * as G from '@/utils/common'
import style from './style.less';

/**
 *  东风 ： 车辆历史档案  T-BOX通讯日志  T-BOX通信业务日志  行车轨迹  远程操作日志  获取T-BOX日志记录
 *  海马： 车辆历史档案   T-BOX通信日志  车辆行车轨迹（暂不开放）
 *  北汽： 车辆历史档案  T-BOX通信业务日志  行车轨迹
 *  五菱： 行车轨迹  车况仪表
 *
 */
const tabList = [
  {
    key: 'vehicle-history',
    tab: '车辆历史档案',
  }, {
    key: 'vehicle-tboxLog',
    tab: 'T-BOX通讯日志',
  }, {
    key: 'vehicle-tboxBusiLog',
    tab: 'T-BOX通信业务日志',
  }, {
    key: 'vehicle-wheelPath',
    tab: '行车轨迹',
  }, {
    key: 'rcUserInfo',
    tab: '远程操作日志',
  }, {
    key: 'canLog',
    tab: '获取T-BOX日志记录',
  }, {
    // key: 'vehicleHM-tboxLog',
    // tab: 'T-BOX通信日志',
  // }, {
  //   key: 'vehicleHM-wheelPath',
  //   tab: '车辆行车轨迹',
  // }, {
    // key: 'vehicle-statusMeter',
    // tab: '车况仪表',
  // },{
    // key: 'vehicleSGMW-wheelPath',
    // tab: '行车轨迹',
  // },{
    key: 'vehicle-timeScaled',
    tab: 'TBOX通信日志时序查询',
  }
]

@connect(({ vehicle,vehicle2,vehicle3,loading }) => ({
  vehicle,
  vehicle2,
  vehicle3,
  detailLoading: loading.effects['vehicle/getVehicleDetail'],
}))
export default class VehicleDetail extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      activeKey: '',
      simDetailVisible: false,
      simDetailModelData: {},
      projectId: '',
    }
    const { location: { rowData, query, sourceName, cloudplat } } = props
    // 防止蓝屏, 把数据存在中sessionStorage
    if (rowData) sessionStorage.setItem('vehicleData', JSON.stringify(rowData))
    if (query) sessionStorage.setItem('query', JSON.stringify(query))
    if (sourceName) sessionStorage.setItem('sourceName', JSON.stringify(sourceName))
    if (cloudplat) sessionStorage.setItem('cloudplat', JSON.stringify(cloudplat))
  }

  static contextTypes = {
    dicData: PropTypes.any,
    authButton: PropTypes.array,
  }

  componentDidMount() {
    this.getVehicleDetail()
    const activeKey = this.getFirstTabkey()
    this.setState({ activeKey })
  }

  componentWillUnmount() {
    // 车辆详情新增车辆位置跳转，故而缓存移除不能放在详情页，移至车辆管理初始化
    // sessionStorage.removeItem('vehicleData')
    // sessionStorage.removeItem('query')
    // sessionStorage.removeItem('sourceName')
  }

  // 获取车辆详情，调用四个接口，分别拿到车辆详情、车主信息、车况、流量
  getVehicleDetail = () => {
    const { dispatch } = this.props;
    const vehicleData = JSON.parse(sessionStorage.getItem('vehicleData'));
    const cloudplat = JSON.parse(sessionStorage.getItem('cloudplat'));
    const { vin, brandId: brand, tbox, pdsn, seriesId } = vehicleData;
    const rtype1 = !cloudplat || cloudplat == null || cloudplat === '' ? 'vehicle/getVehicleDetail' : cloudplat === 'pateo' ? 'vehicle2/getVehicleDetail' : 'vehicle3/getVehicleDetail';
    const rtype2 = !cloudplat || cloudplat == null || cloudplat === '' ? 'vehicle/getVehicleUser' : cloudplat === 'pateo' ? 'vehicle2/getVehicleUser' : 'vehicle3/getVehicleUser';
    const rtype3 = !cloudplat || cloudplat == null || cloudplat === '' ? 'vehicle/getVehicleStatus' : cloudplat === 'pateo' ? 'vehicle2/getVehicleStatus' : 'vehicle3/getVehicleStatus';
    const rtype4 = !cloudplat || cloudplat == null || cloudplat === '' ? 'vehicle/getVehicleFlow' : cloudplat === 'pateo' ? 'vehicle2/getVehicleFlow' : 'vehicle3/getVehicleFlow';
    const rtype5 = !cloudplat || cloudplat == null || cloudplat === '' ? 'extendForm/list' : cloudplat === 'pateo' ? 'extendForm2/list' : 'extendForm3/list';
    dispatch({
      type: rtype1,
      payload: { url: '/vehicle/detail', vin },
    })
    dispatch({
      type: rtype2,
      payload: { url: '/vehicle/owerprofilewithcontact', vin, pdsn, tbox },
    })
    dispatch({
      type: rtype3,
      payload: { url: '/vehicle/vehiclestatus', vin, brand },
    })
    dispatch({
      type: rtype4,
      payload: { url: '/vehicle/vehicleflow', vin, brand, tbox, pdsn, seriesId },
    })
    dispatch({
      type: rtype5,
      payload: { url: '/vehicle/findaccountbydeviceid', deviceId:vin},
      callback: res => this.setState({ projectId: res.data.projectId }),
    })
  }

  getFirstTabkey = () => {
    const authButtons = [] // this.context.authButton
    const authTab = tabList//.filter(item => authButtons.includes(item.key))
    return authTab[0] && authTab[0].key
  }

  onTabChange = key => this.setState({ activeKey: key })

  goVehicleList = () => {
    const { dispatch } = this.props
    const query = JSON.parse(sessionStorage.getItem('query'))
    const sourceName = JSON.parse(sessionStorage.getItem('sourceName'))
    dispatch(routerRedux.push({ pathname: sourceName, state: { query } }))
  }

  // react升级之后，应该把这个移到VehicleFlow中
  handleDetailSIM = (deviceId) => {
    const { dispatch } = this.props
    dispatch({
      type: 'simCard/findById',
      payload: deviceId,
      callback: (simDetail) => {
        if (simDetail.statusCode === '0') {
          this.setState({ simDetailModelData: simDetail.data, simDetailVisible: true })
        } else {
          message.error(simDetail.statusMessage)
        }
      },
    })
  }

  handleAuthTab = (rowData,brand, tbox) => {
    const authButtons = []; // this.context.authButton
    const carSpt=rowData.carSpt;//是否是手机车联网 1:是
    //console.log(carSpt)
    let authTab = tabList//.filter(item => authButtons.includes(item.key))
    if (brand === 'BAIC' && !tbox) {
      authTab = R.take(1, tabList)
    }
    const { seriesId } = JSON.parse(sessionStorage.getItem('vehicleData'))
    const canLogBalcakList = G.getDicByCode(this.context.dicData, 'canLogBalcakList')
    const isexistInBalckList = !!canLogBalcakList.find(item => item.value === seriesId)
    if (brand === 'DFPV' && carSpt!=='1' && isexistInBalckList) {//如果是东风车辆,并且不是手机车联网车,并且是黑名单车系,就移除获取T-BOX日志Tab页
      authTab = R.reject(tab => tab.key === 'canLog', authTab)
    }
    return authTab
  }

  render() {
    let detail = {};
    let status = {};
    let user = {};
    let flow = {};

    const cloudplat = JSON.parse(sessionStorage.getItem('cloudplat'));
    if(!cloudplat || cloudplat == null || cloudplat === '' ) {
      detail = this.props.vehicle.detail.detail;
      status = this.props.vehicle.status.status;
      user = this.props.vehicle.user.user;
      flow = this.props.vehicle.flow.flow;
    } else if (cloudplat === 'pateo') {
      detail = this.props.vehicle2.detail.detail;
      status = this.props.vehicle2.status.status;
      user = this.props.vehicle2.user.user;
      flow = this.props.vehicle2.flow.flow;
    } else {
      detail = this.props.vehicle3.detail.detail;
      status = this.props.vehicle3.status.status;
      user = this.props.vehicle3.user.user;
      flow = this.props.vehicle3.flow.flow;
    }

    const {
      // vehicle: { detail: { detail }, status: { status }, user: { user }, flow: { flow } },
      detailLoading,
    } = this.props
    const { activeKey, simDetailVisible, simDetailModelData, projectId } = this.state
    const rowData = JSON.parse(sessionStorage.getItem('vehicleData'))
    const { brandId, vin, pdsn, tbox } = rowData

    const contentList = {
      'vehicle-history': <DFPVHistoryTab deviceId={vin} />,
      'vehicle-tboxLog': <DFPVTboxLogTab rowData={rowData} />,
      'vehicle-tboxBusiLog': <DFPVTboxBusinessLogTab rowData={rowData} />,
      'vehicle-wheelPath': <DFPVWheelPathTab vin={vin} />,
      rcUserInfo: <DFPVRcUerInfoTab deviceId={vin}  />,
      canLog: <DFPVCanLogTab deviceId={vin} rowData={rowData} />,
      // 'vehicleHM-tboxLog': <HMTboxLogTable vin={vin} pdsn={pdsn} tbox={tbox} />,
      // 'vehicleHM-wheelPath': <HMWheelPathTable vin={vin} />,
      // 'vehicle-statusMeter': <VehicleStatusListTable vin={vin} />,
      // 'vehicleSGMW-wheelPath': <SGMWWheelPathTab vin={vin} />,
      'vehicle-timeScaled' : <TboxTimeScaledTab rowData={rowData} projectId={projectId}/>
    }
    const authTab = this.handleAuthTab(rowData, brandId, tbox)
    if (this.props.location.flag) {
    return (
      <PageHeaderLayout>
        <Card
          style={{ marginBottom: 24 }}
          bordered={false}
          loading={detailLoading}
        >
          <VehicleInfo
            brandId={brandId}
            detail={{ ...rowData, ...detail }}
          />
          <Divider />
          <VehicleStatus brandId={brandId} status={status} dispatch={this.props.dispatch} />
          <Divider />
          <VehicleFlow
            brandId={brandId}
            flow={flow}
            showSimDetail={this.handleDetailSIM}
          />
          <Divider />
          <OwerProfile brandId={brandId} user={user} />
        </Card>
        <Card
          style={{ marginBottom: 24 }}
          bordered={false}
          loading={detailLoading}
          tabList={authTab}
          onTabChange={this.onTabChange}
        >
          {contentList[activeKey]}
        </Card>
        <div className={style.my_bottomBtn}>
          <PrimaryButton title={'返回'} onClick={this.goVehicleList} />
        </div>
        <SIMDetailModal
          changeVisible={() => this.setState({ simDetailVisible: false, simDetailModelData: {} })}
          visible={simDetailVisible}
          detailModelData={simDetailModelData}
        />
      </PageHeaderLayout>
    );
  }else {
      return (
        <PageHeader title="">
          <div align="center" width="100%" height="100%">
            <h2>未选择任何VIN号,请返回列表重新选择</h2>
            <a onClick={this.goBack}>返回</a>
          </div>
        </PageHeader>
      );
    }
  }
}
